package cn.wbu.zyh.controller.common;

import cn.wbu.zyh.constant.JwtClaimsConstant;
import cn.wbu.zyh.dto.EmployeeDTO;
import cn.wbu.zyh.dto.LoginDTO;
import cn.wbu.zyh.entity.Employee;
import cn.wbu.zyh.properties.JwtProperties;
import cn.wbu.zyh.result.Result;
import cn.wbu.zyh.service.EmployeeService;
import cn.wbu.zyh.utils.JwtUtil;
import cn.wbu.zyh.vo.LoginVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/common")
@Slf4j
public class LoginController {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("/login")
    @ApiOperation(value = "用户登陆")
    public Result<LoginVO> login(@RequestBody LoginDTO loginDTO) {
        log.info("员工登录：{}", loginDTO);

        Employee employee = employeeService.login(loginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        LoginVO loginVO = LoginVO.builder()
                .id(employee.getId())
                .userName(employee.getUsername())
                .name(employee.getName())
                .role(employee.getRole())
                .token(token)
                .build();

        return Result.success(loginVO);
    }
    @PostMapping("/register")
    @ApiOperation("用户注册")
    public Result register(@RequestBody EmployeeDTO employeeDTO) {
        log.info("用户注册:{}",employeeDTO);
        employeeService.register(employeeDTO);
        return Result.success();
    }
    @PostMapping("/loginout")
    @ApiOperation("员工退出")
    public Result<String> loginOut() {
        return Result.success("success");
    }
}
